package com.java1234.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.java1234.entity.Gangwei;
import com.java1234.entity.PageBean;
import com.java1234.entity.R;
import com.java1234.service.GangweiService;
import com.java1234.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 岗位 前端控制器
 * </p>
 *
 * @author zhai
 * @since 2025-05-09
 */
@RestController
@RequestMapping("/sys/gangwei")
public class GangweiController {

    @Autowired
    private GangweiService service;

    @PostMapping("/save")
    @PreAuthorize("hasAuthority('system:gangwei:save')")
    public R save(@RequestBody Gangwei entity){
        if(entity.getId()==null || entity.getId()==-1){
            service.save(entity);
        }else{
            service.updateById(entity);
        }
        return R.ok();
    }

    @PostMapping("/list")
    @PreAuthorize("hasAuthority('system:gangwei:list')")
    public R list(@RequestBody PageBean pageBean){
        String query = pageBean.getQuery() != null ? pageBean.getQuery().trim() : "";
        String query2 = pageBean.getQuery2() != null ? pageBean.getQuery2().trim() : "";
        Page<Gangwei> pageResult = service.page(
                new Page<>(pageBean.getPageNum(), pageBean.getPageSize()),
                new QueryWrapper<Gangwei>()
                        .like(StringUtil.isNotEmpty(query), "gangwei", query)
                        .eq(StringUtil.isNotEmpty(query2), "bumenid", query2)
        );
        Map<String,Object> resultMap=new HashMap<>();
        resultMap.put("list",pageResult.getRecords());
        resultMap.put("total",pageResult.getTotal());
        return R.ok(resultMap);
    }

    @PostMapping("/delete")
    @Transactional
    @PreAuthorize("hasAuthority('system:gangwei:delete')")
    public R delete(@RequestBody Long[] ids){
        service.removeByIds(Arrays.asList(ids));
        return R.ok();
    }

    @GetMapping("/info/{id}")
    @PreAuthorize("hasAuthority('system:gangwei:query')")
    public R info(@PathVariable(value = "id") Long id){
        Gangwei entity = service.getById(id);
        Map<String,Object> map=new HashMap<>();
        map.put("gangwei",entity);
        return R.ok(map);
    }
    @PostMapping("/all")
    public R getAllBumen(String bumenId) {
        List<Gangwei> list = service.list(new QueryWrapper<Gangwei>()
                .eq(StringUtil.isNotEmpty(bumenId), "bumenid", bumenId)
        );
        Map<String,Object> resultMap=new HashMap<>();
        resultMap.put("list",list);
        resultMap.put("total",list.size());
        return R.ok(resultMap);
    }
}
